package com.tth.learn.addproperties.java2;

import com.tth.learn.addproperties.java1.Person;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Author tth
 * @Date 2023/1/3 15:55
 */
public class StreamAPITest {

    /**
     * 通过集合实例化
     */
    @Test
    public void test1() {
        List<Person> persons = new ArrayList<Person>(){
            { add(new Person(1001, "张1", 18, 5600)); }
            { add(new Person(1002, "张2", 17, 7200)); }
            { add(new Person(1003, "张3", 16, 3400)); }
            { add(new Person(1004, "张4", 20, 8900)); }
            { add(new Person(1005, "张5", 19, 5400)); }
            { add(new Person(1006, "张6", 18, 5600)); }
        };

        // 创建顺序流
        Stream<Person> stream = persons.stream();

        // 创建并行流
        Stream<Person> personStream = persons.parallelStream();
    }

    /**
     * 通过数组实例化
     */
    @Test
    public void test2() {
        Person[] arr = new Person[] {
                new Person(1001, "张1", 18, 5600),
                new Person(1002, "张2", 17, 7200),
                new Person(1003, "张3", 16, 3400),
                new Person(1004, "张4", 20, 8900),
                new Person(1005, "张5", 19, 5400),
                new Person(1006, "张6", 18, 5600)
        };

        Stream<Person> stream = Arrays.stream(arr);
    }

    /**
     * 通过Stream.of()实例化
     */
    @Test
    public void test3() {
        Stream<Person> stream = Stream.of(new Person(1001, "张1", 18, 5600),
                new Person(1002, "张2", 17, 7200),
                new Person(1003, "张3", 16, 3400),
                new Person(1004, "张4", 20, 8900),
                new Person(1005, "张5", 19, 5400),
                new Person(1006, "张6", 18, 5600));

    }

    /**
     * 创建无限流---用来造数据
     */
    @Test
    public void test4() {
        // 获取前10个偶数
        Stream<Integer> stream1 = Stream.iterate(0, t -> t + 2).limit(10);
        stream1.forEach(System.out :: println);

        System.out.println("********************************");

        // 获取10个随机数
        Stream<Double> stream2 = Stream.generate(Math::random).limit(10);
        stream2.forEach(d -> System.out.println(d));
    }
}
